/**
 * Filename: MusicPhotosActivity.java
 * @author  Firefly
 * @contact postfirefly@163.com
 * @time    2016/5/7 18:23
 */
package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.MusicThemeAdapter;
import com.github.postsanf.yinian.bean.YNMusicTheme;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNMusicPhotoResponse;
import com.github.postsanf.yinian.service.DoBase64Service;
import com.github.postsanf.yinian.service.UpLoadService;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.github.postsanf.yinian.view.DetailRecyclerView;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 音乐相册
 */
public class MusicPhotosActivity extends BaseActivity implements ISkinUpdate,View.OnClickListener {
    private Toolbar             mToolbar;
    private TextView            btn_alert_music;
    private TextView            btn_alert_photo;
    private TextView            btn_alert_title;
    private DetailRecyclerView  rv_music_theme;
    private List<YNMusicTheme>  mMusicTheme = new ArrayList<>();
    private MusicThemeAdapter   mAdapter;
    private ProgressDialog      mProgressDialog;
    private WebView             web;
    private String              current_url="http://www.zhuiyinanian.com/musictemplet/jjf.html";
    private String              response;
    private static final  int   WHAT_UPDATE = 1;
    private boolean             isInitOK;
    private boolean             isGetBase;
    private int                 curID = 1;
    private String              title="";

    Handler handlerHTTP = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_UPDATE:
                    String s= rebuildContent(response);
                    web.loadDataWithBaseURL(null, s, "text/html", "utf-8", null);
                    mProgressDialog.dismiss();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_music_photo);
        registerBroadcastReceiver();
        BaseApplication.getInstance().mActivitys.add(this);
        initView();
    }

    private void  initView() {
        initData();
        mToolbar = (Toolbar) findViewById(R.id.music_photo_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);

        web = (WebView) findViewById(R.id.wv_music_photo);
        int xx = DisplayUtils.getScreenHeightPixels(this) - DisplayUtils.dp2px(this,231);
        web.getLayoutParams().width = xx * 2/3;
        mProgressDialog = ProgressDialog.show(MusicPhotosActivity.this, null, "正在加载...");

        web.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        web.getSettings().setBuiltInZoomControls(true);
        web.getSettings().setJavaScriptEnabled(true);
        web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    // 网页加载完成
                    mProgressDialog.dismiss();
                } else {
                    // 加载中
                    mProgressDialog.show();
                }
            }
        });
        loaddata();
        if (Build.VERSION.SDK_INT >= 19){
            web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        }
        rv_music_theme  = (DetailRecyclerView) findViewById(R.id.rv_music_theme);
        WrapContentLinearLayoutManager horLayoutManager = new WrapContentLinearLayoutManager(this);
        horLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_music_theme.setLayoutManager(horLayoutManager);
        mAdapter = new MusicThemeAdapter(this, mMusicTheme);
        rv_music_theme.setHasFixedSize(true);
        rv_music_theme.setAdapter(mAdapter);

        btn_alert_music = (TextView) findViewById(R.id.btn_alert_music);
        btn_alert_photo = (TextView) findViewById(R.id.btn_alert_photo);
        btn_alert_title = (TextView) findViewById(R.id.btn_alert_title);

        btn_alert_music.setOnClickListener(this);
        btn_alert_photo.setOnClickListener(this);
        btn_alert_title.setOnClickListener(this);

        mAdapter.setOnItemClickLitener(new MusicThemeAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, String url,String wh ,int curid) {
                if (!current_url.equals(url)) {
                    curID = curid;
                    current_url = url;
                    isGetBase = false;
                    isInitOK  = false;
                    // 通知后台转Base64
                    Intent mIntent = new Intent(MusicPhotosActivity.this, DoBase64Service.class);
                    mIntent.setAction(ACTIONs.actionDoBase);
                    mIntent.putExtra(ACTIONs.aWH,wh);
                    startService(mIntent);
                    // 进度条
                    mProgressDialog = ProgressDialog.show(MusicPhotosActivity.this, null, "正在加载...");
                    loaddata();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_publish, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.action_publish:
                publishMusicPhoto();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void publishMusicPhoto(){
        Intent mIntent = new Intent(this,UpLoadService.class);
        mIntent.setAction(ACTIONs.actionPublishPhoto);
        mIntent.putExtra(ACTIONs.aUid, String.valueOf(application.getCurID()));
        mIntent.putExtra(ACTIONs.aGid, String.valueOf(application.getCurGid()));
        mIntent.putExtra(ACTIONs.aGname, YNSingleton.getInstance().getCurAlbum().getGname());
        // aTempletid
        mIntent.putExtra(ACTIONs.aType, curID);
        // aMusicid
        mIntent.putExtra(ACTIONs.aPush, 1);
        // 音乐相册分类
        mIntent.putExtra(ACTIONs.aIsOfficial,2);
        mIntent.putExtra(ACTIONs.aContent,title);
        startService(mIntent);

        intent2Activity(UpLoadActivity.class);
        Intent upIntent = new Intent(ACTIONs.actionCloseAlbum);
        upIntent.putExtra(ACTIONs.aIsClearSelect, 1);
        sendBroadcast(upIntent);
    }

    private void loaddata(){
            new Thread(new Runnable() {
                @Override
                public void run() {
//                    HttpClient httpCient = new DefaultHttpClient();
//                    HttpGet httpGet = new HttpGet(current_url);
//                    try {
//                        HttpResponse httpResponse = httpCient.execute(httpGet);
//                        if (httpResponse.getStatusLine().getStatusCode() == 200) {
//                            HttpEntity entity = httpResponse.getEntity();
//                            response = EntityUtils.toString(entity, "utf-8");
//                            isInitOK = true;
//                            doShowWebInfo();
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                }
            }).start();
    }

    private void doShowWebInfo(){
        if(isInitOK && isGetBase){
            Message message = new Message();
            message.what = WHAT_UPDATE;
            handlerHTTP.sendMessage(message);
        }
    }

    private void initData(){
        LinkedHashMap<String,String> mParam = new LinkedHashMap<>();
        StringRequest req = new StringRequest(getString(R.string.BASE_URL)+getString(R.string.ynShowTempletMusic))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true){
                    @Override
                    public void onSuccess(String s, Response<String> response){
                        YNMusicPhotoResponse resMusicTheme = gson.fromJson(s, YNMusicPhotoResponse.class);
                        if (resMusicTheme!=null && ReqUtils.isSuccess(resMusicTheme.getCode())) {
                            mMusicTheme.clear();
                            mMusicTheme.addAll(resMusicTheme.getData());
                            mAdapter.notifyDataSetChanged();
                        }else{
                            showToast("请求失败");
                        }
                    }
                    @Override
                    public void onFailure(HttpException e, Response<String> response){
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case CommonConstants.REQ_MUSIC_IMAGE:
                loaddata();
                break;
            case CommonConstants.REQ_MUSIC_TITLE:
                if (resultCode == RESULT_CANCELED) {
                    return;
                }
                int tag = data.getIntExtra(CommonConstants.REQ_CODE, 0);
                if (1 == tag) {
                    title = data.getStringExtra(CommonConstants.REQ_DATA);
                    mToolbar.setTitle(title);
                }
                break;
            default:
                break;
        }
    }

    private String  rebuildContent(String s ){
        String rString=s;
        for(int i=1;i<=20;i++){
            rString=rString.replace("###b64" +(21-i), SelectedImg.base64Image.get(20-i));
        }
        return rString;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            // 切换音乐
            case R.id.btn_alert_music:
                intent2Activity(SwitchMusicActivity.class);
                break;
            // 添加图片
            case R.id.btn_alert_photo:
                Intent intent = new Intent(this, SwitchPhotoActivity.class);
                startActivityForResult(intent, CommonConstants.REQ_MUSIC_IMAGE);
                break;
            // 添加标题
            case R.id.btn_alert_title:
                Intent tintent = new Intent(this,SwitchTitleActivity.class);
                tintent.putExtra(CommonConstants.YNDATAS, title);
                startActivityForResult(tintent, CommonConstants.REQ_MUSIC_TITLE);
                break;
        }
    }

    @Override
    public void updateTheme(){
        if(mToolbar!=null){
            try {
                Resources mResource= SkinPackageManager.getInstance(this).mResources;
                mToolbar.setNavigationIcon(mResource.getDrawable(mResource.getIdentifier("ic_return", "drawable", "com.github.postsanf.skinby")));
                mToolbar.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", "color", "com.github.postsanf.skinby")));
                mToolbar.setTitleTextColor(mResource.getColor(mResource.getIdentifier("border_color", "color", "com.github.postsanf.skinby")));
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    // 分析并执行动作
    BroadcastReceiver mMusicPhotoBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent){
            String action = intent.getAction();
            switch (action){
                case ACTIONs.actionUpdateBase:
                    isGetBase = true;
                    doShowWebInfo();
                    break;
                case  ACTIONs.actionCloseAlbum:
                    MusicPhotosActivity.this.finish();
                    break;
            }
        }
    };

    // 注册接收者
    private void registerBroadcastReceiver(){
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionUpdateBase);
        myIntentFilter.addAction(ACTIONs.actionCloseAlbum);
        registerReceiver(mMusicPhotoBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApplication.getInstance().mActivitys.remove(this);
        unregisterReceiver(mMusicPhotoBroadcastReceiver);
    }

    // 友盟统计
    public void onResume(){
        super.onResume();
        if(SkinPackageManager.getInstance(this).mResources!=null){
            updateTheme();
        }
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause(){
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
